package homework.printyourself.danmu.view;

import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;
import java.util.Random;
import java.util.Vector;

public class DanMuPanel extends JPanel {

	final public int DEFAULT_LINE_COUNT = 10;

    private Random random;

    private Vector<DanMuLabel> danMuLabels = new Vector<DanMuLabel>();

    private Timer moveTimer;

    private int tick = 100;

    public DanMuPanel(int width, int height) {
        super();
        this.setLayout(null);
        this.setPreferredSize(new Dimension(width, height));
        this.setSize(width, height);

        random = new Random();
        random.setSeed(System.currentTimeMillis());

        moveTimer = new Timer(tick, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                moveDanMu();
            }
        });
//        moveTimer = new Timer(tick, (e) ->  moveDanMu());
    }

    public DanMuPanel(int width, int height, int tick) {
        this(width, height);
        this.tick = tick;
    }

    public DanMuLabel addDanMu(String content) {
        return addDanMu(content, random.nextInt(DEFAULT_LINE_COUNT), null);
    }

    public DanMuLabel addDanMu(String content, int lineNo, String colorHex) {
        DanMuLabel danMu = new DanMuLabel(content, colorHex).setSpeed(random.nextInt(10));
        addDanMuLabel(danMu, lineNo);
        return danMu;
    }

    public void addDanMuLabel(DanMuLabel danMu, int lineNo) {
        int y = this.getHeight() / DEFAULT_LINE_COUNT * lineNo;
        danMu.setLocation(this.getWidth(), y);

        danMuLabels.add(danMu);
        this.add(danMu);
    }

    public void moveDanMu() {
        for(Iterator<DanMuLabel> it = danMuLabels.iterator(); it.hasNext();) {
            DanMuLabel danMu = it.next();
            danMu.setLocation(danMu.getX() - danMu.getSpeed(), danMu.getY());

            if(danMu.getX() + danMu.getWidth() < 0) {
                this.remove(danMu);
                it.remove();
            }
        }
    }

    public int danMuCount() {
        return danMuLabels.size();
    }

    public void startMovingTimer() {
        if(moveTimer != null && !moveTimer.isRunning())
            moveTimer.start();
    }

    public void pause() {
        if(moveTimer != null && moveTimer.isRunning())
            moveTimer.stop();
    }
}
